from rest_framework import status
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
import random,string,redis,json,re
from captcha.image import ImageCaptcha
from django.http import HttpResponse
from django.db.models import Q
from utils.ip_address.ip_info import CzIp
from staff.models import StaffModel
from utils.utils_token import check_token,login_token
from staff.serializer import *
from management.serializer import *
from rest_framework.viewsets import ModelViewSet
from management.models import *
from rest_framework.pagination import PageNumberPagination
from rest_framework.filters import SearchFilter
# Create your views here.


# 分页的视图
class MyPagination(PageNumberPagination):

    page_size = 3
    max_page_size = 5

    page_query_param = "size"
    page_size_query_param = "pagesize"


# 获取图片验证码
class ImgCode(ViewSet):
    redis_conn = redis.Redis(host='localhost', password='123', db=2, port=6379)
    def image_code(self,request,uuid):
        try:
            salt = "".join(random.sample(string.ascii_letters+string.digits, 4))
            img = ImageCaptcha()
            image = img.generate(salt)
            self.redis_conn.set(f"img_{uuid}", salt, ex=60 * 5)
            # images = image.decode()
            # print("验证码>>>", images)
            return HttpResponse(image,content_type='image/png')
        except Exception as e:
            print("错误>>>>>", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, 'message': f"服务器错误{e}"})


# 登录
class Login(ViewSet):
    redis_conn = redis.Redis(host='localhost', password='123', db=2, port=6379)
    cz = CzIp()

    def login(self,request):
        name = request.data.get('name')
        password = request.data.get('password')
        img_code = request.data.get("img_code")
        uuid = request.data.get("uuid")
        print("账号>>", name)
        print("密码>>>", password)
        print("验证码>>>", img_code)
        print("uuid_>>>", uuid)

        staff = StaffModel.objects.filter(Q(account=name)| Q(mobile=name), is_delete=False).first()
        if not staff:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                'message': "账号不存在",
            })

        pwd = StaffModel.objects.filter(password=password).first()
        if not pwd:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": "密码错误！"
            })
        code = self.redis_conn.get(f"img_{uuid}")
        if code == None:
            return Response({"code": status.HTTP_400_BAD_REQUEST, "message": "验证码已过期！"})
        code = code.decode()
        print('code>>>>>', code)
        if img_code.lower() != code.lower():
            return Response({"code": status.HTTP_400_BAD_REQUEST, "message": "验证码错误！"})
        payload = {
            'id': staff.id,
            'name': staff.name
        }

        token, refresh_token = login_token(payload)
        path = request.path_info
        method = request.method.lower()
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
        address = self.cz.get_addr_by_ip(ip)
        facility = request.headers.get("User-Agent")
        Operate_LogModel.objects.create(name="登录", staff_id=staff.id, path=f"{method} {path}", ip=ip, address=address,
                                        facility=facility)
        return Response({
            "code": status.HTTP_200_OK,
            'message': "登录成功!",
            "token": token,
            'refresh_token': refresh_token,
        })


# 忘记密码
class PutPwd(ViewSet):
    cz = CzIp()
    def update(self,request):
        staff = request.session.get("staff")
        print('token_id', staff)
        staff_id = staff.get('id')
        nickname = request.data.get("nickname")
        password = request.data.get("password")
        upwd = request.data.get("pwd")

        if not password == upwd:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": "密码不一致"
            })
        users = StaffModel.objects.filter(account=nickname).first()
        if not users:
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": "没有该账号！"
            })
        StaffModel.objects.filter(account=nickname).update(password=password)
        path = request.path_info
        method = request.method.lower()
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
        address = self.cz.get_addr_by_ip(ip)
        facility = request.headers.get("User-Agent")
        Operate_LogModel.objects.create(name="找回密码操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                        address=address,
                                        facility=facility)
        return Response({
            "code": status.HTTP_200_OK,
            "message": "修改密码成功"
        })


# 获取所有员工数据
class StaffSList(ModelViewSet):
    queryset = StaffModel.objects.all()
    serializer_class = StaffSer
    filter_backends = [SearchFilter]
    search_fields = ["name", "mobile"]
    cz = CzIp()

    # 获取所有员工数据
    def list(self, request, *args, **kwargs):
        staff = StaffModel.objects.filter(is_delete=False).all()
        len = staff.count()
        staffser = StaffSer(staff, many=True).data
        staffser = json.loads(json.dumps(staffser))
        for i in staffser:
            position = PositionModel.objects.filter(id=i['position_id']).all()
            position_ser = PositionSer(position,many=True)
            position_list = json.loads(json.dumps(position_ser.data))
            for po in position_list:
                i['position'] = po['name']
                rank = RankModel.objects.filter(id=po['rank_id']).first()
                i['rank_id'] = rank.id
                i['rank'] = rank.name
                demp = DepartmentModel.objects.filter(id=po['department_id']).first()
                i['department_id'] = demp.id
                i['department'] = demp.name

        return Response({
            "code": status.HTTP_200_OK,
            "message": "ok",
            "len": len,
            "staff": staffser,
        })

    # 添加员工
    def create(self, request, *args, **kwargs):
        staff = request.session.get("staff")
        print('token_id', staff)
        staff_id = staff.get('id')
        name = request.data.get("name")
        account = request.data.get("account")
        password = request.data.get("password")
        mobile = request.data.get("mobile")
        birthday = request.data.get("birthday")
        region = request.data.get("region")
        position_id = request.data.get('position_id')

        try:
            username = StaffModel.objects.filter(name=name).first()
            if username:
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": "该用户已存在"
                })
            account_info = StaffModel.objects.filter(account=account).first()
            if account_info:
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": "账号已存在"
                })
            phone = StaffModel.objects.filter(mobile=mobile).first()
            if phone:
                return Response({
                    'code': status.HTTP_400_BAD_REQUEST,
                    "message": "手机号已存在"
                })
            staff_data = {
                "name": name,
                "mobile": mobile,
                "account": account,
                "password": password,
                "birthday": birthday,
                "region": region,
                "position_id": position_id,
            }
            # print('ertyuiytrerfghjkjhgf')
            staff_ser = StaffSer(data=staff_data)
            # print('sdaads')
            if not staff_ser.is_valid():
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": staff_ser.errors
                })
            # print('tfyhjkjh')
            staff_ser.save()
            path = request.path_info
            method = request.method.lower()
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            address = self.cz.get_addr_by_ip(ip)
            facility = request.headers.get("User-Agent")
            Operate_LogModel.objects.create(name="添加员工操作", staff_id=staff_id, path=f"{method} {path}", ip=ip,
                                            address=address,
                                            facility=facility)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "添加员工成功！"
            })
        except Exception as e:
            print("错误>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": "服务器错误"
            })


# 获取员工详情
class StaffPars(ViewSet):
    def retrieve(self,request):
        uid = request.data.get("id")
        staff = StaffModel.objects.filter(id=uid).first()
        staffser = StaffSer(staff).data
        staffser = json.loads(json.dumps(staffser))
        print('员工数据>>>', staffser)
        position = PositionModel.objects.filter(id=staff.position_id).first()
        position_ser = PositionSer(position)
        position_list = json.loads(json.dumps(position_ser.data))
        print('职位<>>>', position_list)
        staffser['position'] = position.name
        rank = RankModel.objects.filter(id=position_list['rank_id']).first()
        staffser['rank_id'] = rank.id
        staffser['rank'] = rank.name
        demp = DepartmentModel.objects.filter(id=position_list['department_id']).first()
        staffser['department_id'] = demp.id
        staffser['department'] = demp.name

        return Response({
            "code": status.HTTP_200_OK,
            "message": "获取用户详情成功!",
            "staff": staffser
        })


# 获取收件信息
class EmailView(ModelViewSet):
    queryset = SendToEmailModel.objects.all()
    serializer_class = SendToEmailSer
    def list(self, request, *args, **kwargs):
        is_send = request.data.get("is_send")
        staff = request.session.get("staff")
        staff_id = staff.get("id")

        if is_send == 'true': # 获取已发送邮件
            send_to_list = SendToEmailModel.objects.filter(send_staff_id=staff_id, is_delete=False).all()
        else:
            # 收件箱
            send_to_list = SendToEmailModel.objects.filter(to_staff_id=staff_id, is_delete=False).all()

        send_to_ser = SendToEmailSer(send_to_list, many=True)
        send_to_list = json.loads(json.dumps(send_to_ser.data))

        for i in send_to_list:
            email = EmailModel.objects.filter(id=i['email_id']).first()
            email_ser = EmailSer(email)
            email_list = json.loads(json.dumps(email_ser.data))

            email_append = EmailAppendixModel.objects.filter(email_id=email_list['id']).all()
            email_append_ser = EmailAppendixSer(email_append, many=True)
            email_append_list = json.loads(json.dumps(email_append_ser.data))

            email_list['appendix'] = email_append_list
            i['email'] = email_list

        return Response({
            "code": status.HTTP_200_OK,
            "message": "获取邮件成功！",
            "results": send_to_list
        })

    # 发送邮件
    def create(self, request, *args, **kwargs):
        staff_list = request.data.get("staff_list")
        title = request.data.get('title')
        content = request.data.get('content')
        appendix_list = request.data.get('appendix_list')

        staff = request.session.get('staff')
        send_staff_id = staff.get('id')

        email_data = {
            "title": title,
            "content": content
        }
        email_ser = EmailSer(data=email_data)
        print('email>>', email_ser)
        if not email_ser.is_valid():
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": email_ser.errors
            })

        # 校验邮件附件
        for i in appendix_list:
            appendix_data = {
                "email_id": 0,
                "appendix_url": i
            }
            appendix_ser = EmailAppendixSer(data=appendix_data)
            if not appendix_ser.is_valid():
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": appendix_ser.errors
                })

        # 校验发件人数据
        send_data = {
            "send_staff_id": send_staff_id,
            "email_id": 0,
        }
        send_ser = SendToEmailSer(data=send_data)
        if not send_ser.is_valid():
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": send_ser.errors
            })
        for j in staff_list:
            to_data = {
                "to_staff_id": j,
                "email_id": 0,
            }
            to_ser = SendToEmailSer(data=to_data)
            if not to_ser.is_valid():
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": to_ser.errors
                })
        email_ser.save()
        print('iop>===========', email_ser)
        email_id = email_ser.data.get('id')
        print('id...====================', email_id)

        # 保存邮件附件
        for i in appendix_list:
            appendix_data = {
                "email_id": email_id,
                "appendix_url": i
            }
            appendix_ser = EmailAppendixSer(data=appendix_data)
            if not appendix_ser.is_valid():
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": appendix_ser.errors
                })
            appendix_ser.save()

        # 校验发件人数据
        send_data = {
            "send_staff_id": send_staff_id,
            "email_id": email_id,
        }
        send_ser = SendToEmailSer(data=send_data)
        if not send_ser.is_valid():
            return Response({
                "code": status.HTTP_400_BAD_REQUEST,
                "message": send_ser.errors
            })
        send_ser.save()

        for j in staff_list:
            to_data = {
                "to_staff_id": j,
                "email_id": email_id,
            }
            to_ser = SendToEmailSer(data=to_data)
            if not to_ser.is_valid():
                return Response({
                    "code": status.HTTP_400_BAD_REQUEST,
                    "message": to_ser.errors
                })
            to_ser.save()

        return Response({
            "code": status.HTTP_200_OK,
            "message": "邮件发送成功！"
        })